<!--
 * @Author: aster lipian1004@163.com
 * @Date: 2025-02-20 17:10:53
 * @FilePath: \aster-flowable-uniapp\src\components\form\render\select-multiple.vue
 * @Description: 复选框
 * Copyright (c) 2025 by Aster, All Rights Reserved.
-->
<template>
  <van-field
    v-if="!_hidden"
    v-model="valueText"
    :name="formItemProp"
    :readonly="true"
    :required="_required"
    :rules="_rules"
    :input-align="FieldInputAlignEnum.RIGHT"
    :error-message-align="FieldInputAlignEnum.RIGHT"
    :label-width="showLabel ? '' : '5rpx'"
    :placeholder="_placeholder"
    is-link
    @click="handleOpen"
  >
    <template #label>
      <text v-if="showLabel">{{ formItem.title }}</text>
    </template>
    <template #extra>
      <view class="field-right" v-if="isNotEmpty(_value)">
        <van-tag
          type="primary"
          v-for="(item, index) in _value"
          :key="index"
          style="margin-right: 6rpx"
        >
          <text class="p-6rpx">{{ item }}</text>
        </van-tag>
      </view>
    </template>
  </van-field>
  <van-popup v-model:show="showPicker" round position="bottom">
    <van-checkbox-group v-if="!_readonly" v-model="_value" class="py-40rpx">
      <van-cell-group inset v-if="options && options.length > 0">
        <van-cell
          v-for="(item, index) in options"
          clickable
          :key="index"
          :title="item.label"
          class="my-20rpx"
        >
          <template #right-icon>
            <van-checkbox :name="item.label" @click.stop />
          </template>
        </van-cell>
      </van-cell-group>
    </van-checkbox-group>
  </van-popup>
</template>
<script setup lang="ts">
  import { useAppStore } from '@/store/modules/app';
  import { evaluateFormula } from '@/utils/workflow';
  import { computed, PropType, ref, watch } from 'vue';
  import { getDictDataList } from '@/utils';
  import { isNotEmpty } from '@/utils/is';
  import { instanceListByCodeApi } from '@/api/workflow/process';
  import { FormPermissionEnum } from '@/enums/workFlowEnum';
  import { FieldInputAlignEnum } from '@/enums/formEnum';

  const emit = defineEmits(['update:value']);
  const props = defineProps({
    value: {
      type: Array as PropType<string[]>,
      default: () => [],
    },
    mode: {
      type: String as PropType<'design' | 'form' | 'search' | 'table' | 'print'>,
      default: 'design',
    },
    formData: {
      type: Object as PropType<WorkForm.FormDataModel>,
      default: {},
    },
    formItem: {
      type: Object as PropType<WorkComponent.ComponentConfig>,
      default: {},
    },
    tableId: {
      type: String,
      default: '',
    },
    tableIndex: {
      type: Number,
      default: 0,
    },
    showLabel: {
      type: Boolean,
      default: true,
    },
  });

  // 字典
  const appStore = useAppStore();
  // 选项
  const options = ref<any[]>([]);
  // VanField值
  const valueText = ref('');
  // 显示弹出层
  const showPicker = ref(false);

  // 打开弹出层
  const handleOpen = () => {
    if (!_readonly.value) {
      showPicker.value = true;
    }
  };

  // 键
  const formItemProp = computed(() => {
    if (isNotEmpty(props.tableId)) {
      return props.tableId + '.' + props.tableIndex + '.' + props.formItem.id;
    } else {
      return props.formItem.id;
    }
  });

  /**
   * @description: 获取动态选项
   * @return {*}
   */
  const getDynamicOptions = async () => {
    if (
      isNotEmpty(props.formItem.props.dynamic.value) &&
      props.formItem.props.dynamic.value.length == 3
    ) {
      await instanceListByCodeApi(props.formItem.props.dynamic.value[1], '9').then(({ data }) => {
        if (data && data.length > 0) {
          options.value = data.map((item: Process.InstanceInfo) => {
            const fieldId = props.formItem.props.dynamic.value[2];
            const label = item[fieldId];
            return {
              value: label,
              label: label,
            };
          });
        } else {
          options.value = [];
        }
      });
    } else {
      options.value = [];
    }
  };

  /**
   * @description: 根据选项类型获取选项值
   * @param {*} type 选项类型
   * @return {*}
   */
  const handleOptions = async (type: string) => {
    if (type === 'static') {
      options.value = props.formItem.props.options.map((item) => {
        return {
          label: item,
          value: item,
        };
      });
    } else if (type === 'dict') {
      const dataList = getDictDataList(appStore.dictList, props.formItem.props.dictType);
      options.value = dataList.map((item) => {
        return {
          label: item.dictLabel,
          value: item.dictLabel,
        };
      });
    } else if (type === 'dynamic') {
      await getDynamicOptions();
    } else {
      options.value = [];
    }
  };

  // 监听选项类型变化
  watch(
    () => props.formItem.props.type,
    async (type: string) => {
      // 根据选项类型获取选项值
      await handleOptions(type);
    },
    { immediate: true, deep: true },
  );

  /**
   * @description: 提示词
   */
  const _placeholder = computed(() => {
    if (_readonly.value) {
      return '';
    }
    return isNotEmpty(_value.value) ? '' : '请选择';
  });

  /**
   * @description: 是否必填, true-必填
   */
  const _required = computed(() => {
    return props.formItem.props.required;
  });

  /**
   * @description: 校验规则
   */
  const _rules = computed(() => {
    const isRequired = _required.value;
    if (props.mode != 'form') {
      return [];
    }
    return isRequired ? [{ required: true, message: `请输入${props.formItem.title}` }] : [];
  });

  /**
   * @description: 组件值
   */
  const _value = computed({
    get() {
      return props.value;
    },
    set(val) {
      emit('update:value', val);
    },
  });

  /**
   * @description: 是否隐藏, true-隐藏
   */
  const _hidden = computed(() => {
    let r = false;
    // 解析隐藏条件公式
    if (props.formItem.props.hidden) {
      let expression = props.formItem.props.hidden;
      // 如果是子表中的控件，则需要用到下标
      if (isNotEmpty(props.tableId)) {
        expression = expression.replaceAll('?', props.tableIndex);
      }
      r = evaluateFormula(expression, props.formData);
    }
    // 判断流程节点下该控件是否隐藏
    if (props.formItem.operation && props.formItem.operation.length > 0) {
      r = r || props.formItem.operation[0] == FormPermissionEnum.HIDDEN;
    }
    return r;
  });

  /**
   * @description: 是否只读, true-只读
   */
  const _readonly = computed(() => {
    let r = props.formItem.props.readonly;
    if (props.formItem.operation && props.formItem.operation.length > 0) {
      r = r || props.formItem.operation[0] == FormPermissionEnum.READONLY;
    }
    return r;
  });

  defineExpose({
    _hidden,
  });
</script>
<style scoped lang="scss">
  .field-right {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
  }
</style>
